
async function getAiModelAnswerStream() {
  const { ctx } = this
  try {
    const { 
      prompt = "你好",
      model = "deepseek-ai/deepseek-r1",
      temperature = 1.2,
      top_p = 0.98,
      max_tokens = 4096,
      baseURL = 'https://integrate.api.nvidia.com/v1',
      apiKey = process.env.NVIDIA_API_KEY || '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'
    } = ctx.request.body

    const axios = require('axios');

    // 设置响应头,支持流式输出
    ctx.set({
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
    });

    let isEnded = false; // 添加标志位

    const response = await axios({
      method: 'post',
      url: `${baseURL}/chat/completions`,
      data: {
        model,
        messages: [{"role": "user", "content": prompt}],
        temperature,
        top_p,
        max_tokens,
        stream: true
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`,
      },
      responseType: 'stream'
    });

    response.data.on('data', chunk => {
      console.log(`chunk ==> `, chunk)
      if (isEnded) return; // 如果已经结束就不再写入
      const lines = chunk.toString().split('\n');
      lines.forEach(line => {
        if (line.trim().startsWith('data: ')) {
          try {
            const data = JSON.parse(line.replace('data: ', ''));
            const content = data.choices[0]?.delta?.content || '';
            if (content && !isEnded) {
              ctx.res.write(`data: ${JSON.stringify({content})}\n\n`);
            }
          } catch(e) {}
        }
      });
    });

    response.data.on('end', () => {
      if (!isEnded) {
        isEnded = true;
        ctx.res.end();
      }
    });

  } catch (e) {
    console.log('ai model stream error:', e);
    if (!ctx.res.writableEnded) {
      ctx.body = {
        code: -1,
        data: e,
        msg: 'failed'
      }
    }
  }